package com.ruoyi.xqsp.controller;

import cn.hutool.core.util.RandomUtil;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.xqsp.constant.MyReturnCode;
import com.ruoyi.xqsp.utils.SmsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.util.SecurityConstants;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

@Api(value = "短信管理",tags = "短信管理")
@RestController
@RequestMapping("/xqsp/phone")
@Slf4j
public class PhoneController {
    @Autowired
    private RedisTemplate redisTemplate;



    @ApiOperation("发送短信验证码")
    @GetMapping("/code/{phone}")
    public AjaxResult sendSmsCode(@PathVariable("phone") String phone) {
        String signName = "州再商贸";
        String templateCode = "SMS_223105049";
        String key = Constants.VER_CODE_DEFAULT +  phone;
        Long seconds = redisTemplate.opsForValue().getOperations().getExpire(key);

        if (seconds > 240) {
            return AjaxResult.error(MyReturnCode.ERR_70001.getCode(), MyReturnCode.ERR_70001.getMsg());
        }

        String code = RandomUtil.randomNumbers(Integer.parseInt("5"));

        System.out.println(phone+":" +code);

        redisTemplate.opsForValue().set(key, code, 300, TimeUnit.SECONDS);
        SmsUtils.sendSms(signName, phone, templateCode, "{\"code\":\""+code+"\"}");
        return AjaxResult.success();
    }


    public static void main(String[] args) throws Exception {

        String result = requestData("https://webapi.sms.mob.com/sms/verify",
                "appkey=3687fbaba5a26&phone=18701996232&zone=86&code=123456");
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject.get("status").equals(468));
    }



    /**
     * 发起https 请求
     * @param address
     * @param params
     * @return
     */
    public  static String requestData(String address ,String params){

        HttpURLConnection conn = null;
        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
                public X509Certificate[] getAcceptedIssuers(){return null;}
                public void checkClientTrusted(X509Certificate[] certs, String authType){}
                public void checkServerTrusted(X509Certificate[] certs, String authType){}
            }};

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());

            //ip host verify
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return urlHostName.equals(session.getPeerHost());
                }
            };

            //set ip host verify
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            URL url = new URL(address);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");// POST
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            // set params ;post params
            if (params!=null) {
                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.write(params.getBytes(Charset.forName("UTF-8")));
                out.flush();
                out.close();
            }
            conn.connect();
            //get result
            StringBuilder result = new StringBuilder();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String ret = "";
                while ((ret = br.readLine()) != null)
                {
                    if (ret != null && !"".equals(ret.trim()))
                    {
                        result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                    }
                }
                log.info("recv - {}", result);
                conn.disconnect();
                br.close();
//                String result = parsRtn(conn.getInputStream());
                return result.toString();
            } else {
                System.out.println(conn.getResponseCode() + " "+ conn.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.disconnect();
        }
        return null;
    }

}
